--
-- @Author:      feilong
-- @DateTime:    2019-10-30 23:05:48
-- @Description: 
-- 服务间共享配置


local skynet = require "skynet"
local sharedata = require("skynet.sharedata")
local server_config = dofile(skynet.getenv("server_config"))
local table_insert = table.insert
local table_remove = table.remove

local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor()
    

    self:register()

end

--注册本服务里的消息
function MessageHandler:register()
    self.message_dispatch = g.MsgDis()
    self.message_dispatch:register('start', handler(self, self.start))
    self.message_dispatch:register('load', handler(self, self.load))
    self.message_dispatch:register('reload', handler(self, self.reload))
    
end


--从本地加载配置文件
function MessageHandler:loadFromLocal()
    self.configs = {}
    local config_path = server_config.config_path
    local file_list = {}
    for filename in lfs.dir(config_path) do
        if filename:find('%.lua$') then
            table_insert(file_list,{
                path = config_path .. '/' .. filename,
                name = filename
            })
        end
    end

    for _,info in ipairs(file_list) do
        local s = info.name
        local key = s:sub(1,-s:reverse():find('%.') - 1) --文件名作为key
        local f = assert(io.open(info.path))
        -- g.Log():debug(key,info.path)
        local source = f:read "*a"
        f:close()
        self.configs[key] = load(source)()
    end
    self:load(self.configs)
    -- print(self.configs)
end


---------------------------------------------------------
-- cmd
---------------------------------------------------------

--启动
function MessageHandler:start()

    self:loadFromLocal()
end


--
function MessageHandler:load(hot_configs)
    -- g.Log():debug("_________收到__load____",hot_configs)
    for key, conf in pairs(hot_configs) do
        sharedata.new(key, conf)
    end
end

--收到别的服务器注册
function MessageHandler:reload(hot_configs)
    g.Log():debug("_________收到__reload____",hot_configs)
    for key, conf in pairs(hot_configs) do
        sharedata.update(key, conf)
    end
end




return MessageHandler

